<template>
  <!-- 工艺参数监控规则表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '1260px' : '1260px'"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="106"
        v-show="!props.isReadonly"
      >
        <!-- <h4 class="mb-[20px] mt-[0px]">基本数据</h4> -->
        <div>
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="工段"
                prop="workshopSectionId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.workshopSectionId"
                  v-if="!props.isReadonly"
                  placeholder="请选择工段"
                  clearable
                  filterable
                  @change="changeWorkshopSection"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in workshopSectionList"
                    :key="item.id"
                    :label="`${item.workshopSectionCode}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.workshopSectionId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工序" prop="processId" style="width: 100%">
                <el-select
                  v-model="formData.processId"
                  v-if="!props.isReadonly"
                  placeholder="请选择工序"
                  clearable
                  filterable
                  @change="changeProcess"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in processList"
                    :key="item.id"
                    :label="`${item.processCode}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.processId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="生产线"
                prop="processEquipId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.processEquipId"
                  v-if="!props.isReadonly"
                  placeholder="请选择生产线"
                  clearable
                  filterable
                  :filter-method="customFilter1"
                  @change="changeProcessEquip"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in filteredOptions1"
                    :key="item.id"
                    :label="`${item.equipCode}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.processId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备" prop="equipId" style="width: 100%">
                <el-select
                  v-model="formData.equipId"
                  v-if="!props.isReadonly"
                  placeholder="请选择设备"
                  clearable
                  filterable
                  @change="changeEquip"
                  :filter-method="customFilter"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in filteredOptions"
                    :key="item.id"
                    :label="`${item.equipName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.equipId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户" prop="projectId" style="width: 100%">
                <el-select
                  v-model="formData.projectId"
                  v-if="!props.isReadonly"
                  placeholder="请选择客户"
                  clearable
                  filterable
                  @change="changeProject"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in projectList"
                    :key="item.id"
                    :label="`${item.projectCode}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.projectId }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item
                label="产品"
                prop="productModel"
                style="width: 100%"
                :disabled="!formData.projectId"
              >
                <el-select
                  v-model="formData.productModel"
                  v-if="!props.isReadonly"
                  placeholder="请选择产品"
                  clearable
                  filterable
                  :disabled="!formData.projectId"
                  @change="changeProductModel"
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in productModelList"
                    :key="item.id"
                    :label="`${item.productCode}`"
                    :value="item.productCode"
                  />
                </el-select>
                <span v-else>{{ formData.productModel }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="第一责任人"
                prop="responsiblePersonId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.responsiblePersonId"
                  v-if="!props.isReadonly"
                  placeholder="请选择第一责任人"
                  clearable
                  style="width: 90%"
                  :disabled="!formData.workshopSectionId"
                  @change="changeResponsible"
                >
                  <el-option
                    v-for="item in userList"
                    :label="`${item.userName}`"
                    :value="`${item.userId}`"
                    :key="item.userId"
                  />
                </el-select>
                <span v-else>{{ formData.responsiblePersonName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否启用" prop="enabled">
                <template v-if="!props.isReadonly">
                  <el-radio-group v-model="formData.enabled">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </template>
                <span v-else>{{
                  dictionaryStore.filterDictName("YesNo", formData.enabled)
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-tabs
          v-if="!props.isReadonly"
          type="border-card"
          v-model="activeTabs"
          @tab-click="handleTabClick"
          style="display: inline-block; margin-right: 30px; width: 100%"
        >
          <el-tab-pane name="监控参数详情" label="监控参数详情">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
              v-if="!props.isReadonly"
            >
              <!-- <h4 class="mb-[15px] mt-[20px]">监控参数详情</h4> -->
              <div></div>
              <el-button
                type="success"
                plain
                @click="handleAdd"
                class="mb-[5px]"
                v-if="!props.isReadonly"
              >
                <i-ep-plus />
                新增
              </el-button>
            </div>
            <div class="formTable">
              <el-table
                :data="formData.details"
                v-loading="laodingTable"
                style="width: 100%"
                :key="Math.random"
                max-height="calc(100vh - 170px - 200px - 70px)"
                border
              >
                <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  min-width="60"
                />
                <el-table-column
                  label="参数名称"
                  props="parameterDesc"
                  min-width="170"
                >
                  <template #default="{ $index, row }">
                    <!-- <el-form-item
                      :prop="'details.' + $index + '.parameterDesc'"
                      :rules="rules.sonparameterDesc"
                      label-width="0"
                    > -->
                    <!-- <el-input
                        v-if="!props.isReadonly"
                        v-model="row.parameterDesc"
                        placeholder="请输入参数名称"
                        clearable
                      /> -->
                    <span>{{ row.parameterDesc }}</span>
                    <!-- </el-form-item> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="工艺数据类别"
                  props="processDataType"
                  min-width="100"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.processDataType'"
                      :rules="rules.sonprocessDataType"
                      label-width="0"
                    >
                      <el-select
                        v-if="!props.isReadonly"
                        v-model="row.processDataType"
                        clearable
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in dictionaryStore.filterDictList(
                            'processDataType'
                          )"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{
                        dictionaryStore.filterDictName(
                          "processDataType",
                          row.processDataType
                        )
                      }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="监控数据类型"
                  props="monitorDataType"
                  min-width="100"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.monitorDataType'"
                      :rules="rules.sonmonitorDataType"
                      label-width="0"
                    >
                      <el-select
                        v-if="!props.isReadonly"
                        v-model="row.monitorDataType"
                        clearable
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in dictionaryStore.filterDictList(
                            'PsmMonitorDataType'
                          )"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <span v-else>{{
                        dictionaryStore.filterDictName(
                          "PsmMonitorDataType",
                          row.monitorDataType
                        )
                      }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="参考值"
                  props="parameterValue"
                  min-width="80"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.parameterValue'"
                      :rules="rules.sonparameterValue"
                      label-width="0"
                    >
                      <el-input
                        v-if="!props.isReadonly"
                        v-model="row.parameterValue"
                        placeholder="请输入"
                        clearable
                      />
                      <span v-else>{{ row.parameterValue }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="控制范围下限"
                  props="lowerLimitValue"
                  min-width="90"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.lowerLimitValue'"
                      :rules="rules.sonlowerLimitValue"
                      label-width="0"
                    >
                      <el-input
                        v-if="!props.isReadonly"
                        v-model="row.lowerLimitValue"
                        placeholder="请输入"
                        clearable
                      />
                      <span v-else>{{ row.lowerLimitValue }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="控制范围上限"
                  props="upperLimitValue"
                  min-width="90"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.upperLimitValue'"
                      :rules="rules.sonupperLimitValue"
                      label-width="0"
                    >
                      <el-input
                        v-if="!props.isReadonly"
                        v-model="row.upperLimitValue"
                        placeholder="请输入"
                        clearable
                      />
                      <span v-else>{{ row.upperLimitValue }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="采样频度"
                  props="samplingFrequency"
                  min-width="110"
                  align="center"
                >
                  <template #default="{ $index, row }">
                    <!-- <el-form-item
                      :prop="'details.' + $index + '.samplingFrequency'"
                      :rules="rules.sonsamplingFrequency"
                      label-width="0"
                    > -->
                    <!-- <el-input
                        v-if="!props.isReadonly"
                        v-model="row.samplingFrequency"
                        placeholder="请输入采样频度"
                        clearable
                      /> -->
                    <div
                      class="cursor-pointer c-[#333] underline"
                      @click="openSampling(row, $index)"
                    >
                      <span>
                        {{
                          useDictionary(
                            "ScaCollectFrequency",
                            row.samplingFrequency
                          )
                        }}
                      </span>
                      <span
                        v-if="
                          row.collectionFrequencyTime &&
                          row.samplingFrequency == '2'
                        "
                        >&nbsp; {{ row.collectionFrequencyTime
                        }}{{
                          row.collectionFrequencyUnit === "s"
                            ? "秒"
                            : row.collectionFrequencyUnit === "m"
                            ? "分钟"
                            : ""
                        }}
                      </span>
                    </div>
                    <!-- </el-form-item> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="生成工单"
                  props="isGenerateWorkOrder"
                  min-width="70"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.isGenerateWorkOrder'"
                      :rules="rules.sonisGenerateWorkOrder"
                      label-width="0"
                      class="switchLable"
                    >
                      <el-switch
                        v-model="row.isGenerateWorkOrder"
                        :active-value="1"
                        :inactive-value="0"
                        :disabled="props.isReadonly"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="发送邮件"
                  props="isSendMail"
                  min-width="70"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.isSendMail'"
                      :rules="rules.sonisSendMail"
                      label-width="0"
                      class="switchLable"
                    >
                      <el-switch
                        v-model="row.isSendMail"
                        :active-value="1"
                        :inactive-value="0"
                        :disabled="props.isReadonly"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="第一责任人"
                  props="responsiblePersonId"
                  min-width="100"
                >
                  <template #default="{ $index, row }">
                    <el-form-item
                      :prop="'details.' + $index + '.responsiblePersonId'"
                      :rules="rules.sonresponsiblePersonId"
                      label-width="0"
                    >
                      <!-- <el-input
                        v-if="!props.isReadonly"
                        v-model="row.responsiblePersonName"
                        placeholder="请输入第一负责人"
                        clearable
                      /> -->
                      <el-select
                        style="width: 100%"
                        v-if="!props.isReadonly"
                        v-model="row.responsiblePersonId"
                        placeholder="请选择"
                        clearable
                        @change="(e) => changePerson(e, $index)"
                      >
                        <el-option
                          v-for="item in userList"
                          :label="`${item.userName}`"
                          :value="`${item.userId}`"
                          :key="`${item.userId}`"
                        />
                      </el-select>
                      <span v-else>{{ row.responsiblePersonName }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="100"
                  v-if="!props.isReadonly"
                >
                  <template #default="scope">
                    <el-button
                      link
                      size="small"
                      type="primary"
                      @click="openChangeRecordDialog(scope.row.id)"
                      >变更记录</el-button
                    >
                    <el-button
                      :disabled="formData.details.length < 2"
                      type="danger"
                      link
                      @click.stop="handleDelete(scope.$index)"
                      ><i-ep-delete />
                      <!-- 删除 -->
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane name="变更记录" label="变更记录">
            <psmparammonitorrule-allchangerecord />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- <h4 class="mb-[20px] mt-[0px]" v-show="props.isReadonly">基础数据</h4> -->
      <el-descriptions
        class="margin-top"
        title=""
        :column="4"
        border
        v-show="props.isReadonly"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工段</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.workshopSectionCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工序</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">生产线</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processEquipCode }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.equipName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">零件名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.partName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">客户</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.projectName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">型号描述</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.productModelName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">产品型号</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.productModel }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">程序名</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.programName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">第一责任人</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData?.responsiblePersonName || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.enabled == 1" type="success">是</el-tag>
            <el-tag v-show="formData.enabled != 1" type="info">否</el-tag>
            <!-- {{
              dictionaryStore.filterDictName("YesNo", formData.enabled) || ""
            }} -->
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <el-tabs
        v-if="props.isReadonly"
        type="border-card"
        v-model="activeTabs"
        @tab-click="handleTabClick"
        style="
          display: inline-block;
          margin-right: 30px;
          width: 100%;
          margin-top: 20px;
        "
      >
        <el-tab-pane name="监控参数详情" label="监控参数详情">
          <div class="formTable3">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              v-show="props.isReadonly"
              max-height="calc(100vh - 170px - 200px)"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                min-width="60"
              />
              <el-table-column
                label="参数名称"
                props="parameterDesc"
                min-width="170"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.parameterDesc }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="工艺数据类别"
                props="processDataType"
                min-width="100"
                align="center"
              >
                <template #default="{ $index, row }">
                  <span>{{
                    dictionaryStore.filterDictName(
                      "processDataType",
                      row.processDataType
                    )
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="监控数据类型"
                props="monitorDataType"
                min-width="100"
                align="center"
              >
                <template #default="{ $index, row }">
                  <span>{{
                    dictionaryStore.filterDictName(
                      "PsmMonitorDataType",
                      row.monitorDataType
                    )
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="参数值"
                props="parameterValue"
                min-width="60"
                align="right"
              >
                <template #default="{ $index, row }">
                  {{ row.parameterValue }}
                </template>
              </el-table-column>
              <el-table-column
                label="控制范围下限"
                props="lowerLimitValue"
                min-width="90"
                align="right"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.lowerLimitValue }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="控制范围上限"
                props="upperLimitValue"
                min-width="90"
                align="right"
              >
                <template #default="{ $index, row }">
                  {{ row.upperLimitValue }}
                </template>
              </el-table-column>
              <el-table-column
                label="采样频度"
                props="samplingFrequency"
                min-width="80"
                align="center"
              >
                <template #default="{ $index, row }">
                  <span>
                    {{
                      useDictionary(
                        "ScaCollectFrequency",
                        row.samplingFrequency
                      )
                    }}
                  </span>
                  <span
                    v-if="
                      row.collectionFrequencyTime &&
                      row.samplingFrequency == '2'
                    "
                    >&nbsp; {{ row.collectionFrequencyTime
                    }}{{
                      row.collectionFrequencyUnit === "s"
                        ? "秒"
                        : row.collectionFrequencyUnit === "m"
                        ? "分钟"
                        : ""
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="生成工单"
                props="isGenerateWorkOrder"
                min-width="72"
                class="switchLable"
              >
                <template #default="{ $index, row }">
                  <div class="flex justify-center">
                    <el-switch
                      v-model="row.isGenerateWorkOrder"
                      disabled
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="发送邮件"
                props="isSendMail"
                min-width="72"
              >
                <template #default="{ $index, row }">
                  <div class="flex justify-center">
                    <el-switch
                      v-model="row.isSendMail"
                      disabled
                      :active-value="1"
                      :inactive-value="0"
                    />
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                label="第一负责人"
                props="responsiblePersonName"
                min-width="100"
                align="center"
              >
                <template #default="{ $index, row }">
                  <span>{{ row.responsiblePersonName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="70" align="center">
                <template #default="{ $index, row }">
                  <!-- <span>{{ row.responsiblePersonName }}</span> -->
                  <el-button
                    size="small"
                    type="primary"
                    link
                    @click="openChangeRecordDialog(row.id)"
                    >变更记录</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane name="变更记录" label="变更记录">
          <psmparammonitorrule-allchangerecord />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 设备选择 -->
    <psmparammonitorrule-select
      v-model:visible="selectDialog.visible"
      :equipId="formData.equipId"
      :equipName="formData.equipName"
      :equipCode="equipCodes"
      :data="breakList"
      @echo-info="changeVisible"
      @update:visible="selectDialog.visible = $event"
    />

    <el-dialog
      v-model="dialogFormVisible"
      title="修改采样频度"
      width="450"
      align-center
    >
      <el-form :model="formTable" :rules="rules1" ref="formRef1">
        <el-form-item
          label="采样方式"
          prop="samplingFrequency"
          style="width: 400px"
        >
          <el-select
            v-model="formTable.samplingFrequency"
            placeholder="请选择采样方式"
            style="width: 100%"
          >
            <el-option
              v-for="item in useDictionary('ScaCollectFrequency')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="采样频度"
          v-if="formTable.samplingFrequency == '2'"
          prop="collectionFrequencyTime"
          style="width: 400px"
        >
          <el-input
            v-model="formTable.collectionFrequencyTime"
            autocomplete="off"
            placeholder=""
          >
            <template #append>
              <el-select
                v-model="formTable.collectionFrequencyUnit"
                placeholder=""
                style="width: 70px"
              >
                <el-option label="秒" value="s" />
                <el-option label="分钟" value="m" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSampling"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <psmparammonitorrule-difftable
      v-model:visible="diffDialog.visible"
      :diffTextArray="diffDialog.diffTextArray"
      :title="diffDialog.title"
      :isReadonly="diffDialog.isReadonly"
      @change-visible="changeDiffVisible"
      @handle-submit="diffSubmit"
    />
    <psmparammonitorrule-changerecord
      v-model:visible="changeRecordDialog.visible"
      :title="changeRecordDialog.title"
      :isReadonly="changeRecordDialog.isReadonly"
      :id="changeRecordDialog.id"
      @change-visible="changeChangeRecordVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { validateNumber, validateNumberCanNot1 } from "@/utils/commonHooks";
import { getMdmProcessEquipApi } from "@/utils/commonData";
import SearchFormGroup from "@/views/eam/qr/common/SearchFormGroupQR.vue";
import useEvent from "@/utils/useEvent";
import _ from "lodash-es";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPSMPARAMMONITORRULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const { eventBusEmit } = useEvent();

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const laodingTable = ref(false);

const dialogFormVisible = ref(false);
const formTable = reactive({
  samplingFrequency: "",
  collectionFrequencyTime: "",
  collectionFrequencyUnit: "",
  index: 0,
});
function openSampling(row: any, index: number) {
  formTable.index = index;
  formTable.samplingFrequency = row.samplingFrequency;
  formTable.collectionFrequencyTime = row.collectionFrequencyTime || "";
  formTable.collectionFrequencyUnit = row.collectionFrequencyUnit || "s";
  dialogFormVisible.value = true;
  setTimeout(() => {
    formRef1.value.clearValidate();
  }, 100);
}
const rules1 = reactive({
  samplingFrequency: [
    { required: true, message: "请选择采样方式", trigger: "change" },
  ],
  collectionFrequencyTime: [
    { required: true, message: "请输入采样频度", trigger: "blur" },
    { required: true, validator: validateNumber, trigger: "blur" },
  ],
});
const formRef1 = ref();

function confirmSampling() {
  formRef1.value.validate(async (valid: any) => {
    if (valid) {
      formData.details[formTable.index].samplingFrequency =
        formTable.samplingFrequency;
      if (formTable.samplingFrequency == "2") {
        formData.details[formTable.index].collectionFrequencyTime =
          formTable.collectionFrequencyTime;
        formData.details[formTable.index].collectionFrequencyUnit =
          formTable.collectionFrequencyUnit;
      } else {
        formData.details[formTable.index].collectionFrequencyTime = "";
        formData.details[formTable.index].collectionFrequencyUnit = "";
      }
      dialogFormVisible.value = false;
    } else {
    }
  });
}

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    // 负责人
    setTimeout(() => {
      formRef.value.clearValidate();
      getUserList(formData.workshopSectionId);
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  processId: "",
  processEquipId: "",
  processEquipCode: "",
  processCode: "",
  workshopSectionCode: "",
  workshopSectionName: "",
  workshopSectionId: "",
  partName: "",
  processName: "",
  equipId: "",
  equipName: "",
  equipCode: "",
  projectId: "",
  projectName: "",
  projectCode: "",
  productModel: "",
  productModelCode: "",
  productModelName: "",
  programName: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  responsiblePersonId: "",
  responsiblePersonName: "",
  changeReason: "",
  changeReasonTime: "",
  details: [
    // {
    //   id: "",
    //   version: "",
    //   ruleId: "",
    //   parameterId: "",
    //   parameterName: "",
    //   parameterDesc: "",
    //   processDataType: "",
    //   parameterValue: "",
    //   lowerLimitValue: "",
    //   upperLimitValue: "",
    //   samplingFrequency: "",
    //   isGenerateWorkOrder: "",
    //   responsiblePersonId: "",
    //   responsiblePersonName: "",
    //   enabled: "",
    //   deleted: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  processId: [{ required: true, message: "请选择工序", trigger: "change" }],
  processEquipId: [
    { required: true, message: "请选择生产线", trigger: "change" },
  ],
  equipId: [{ required: true, message: "请选择设备", trigger: "change" }],
  projectId: [{ required: true, message: "请选择客户", trigger: "change" }],
  productModel: [
    { required: true, message: "请选择产品型号", trigger: "change" },
  ],
  programName: [],
  sonparameterDesc: [
    { required: true, message: "请输入参数名称", trigger: "blur" },
  ],
  sonprocessDataType: [
    {
      required: true,
      message: "请选择工艺数据类别",
      trigger: "change",
    },
  ],
  sonmonitorDataType: [
    {
      required: true,
      message: "请选择监控数据类型",
      trigger: "change",
    },
  ],
  sonparameterValue: [
    // { required: true, message: "请输入参数值", trigger: "blur" },
    { validator: validator1, trigger: "blur" },
  ],
  sonlowerLimitValue: [
    // { required: true, message: "请输入控制范围下限值", trigger: "blur" },
    { validator: validator, trigger: "blur" },
  ],
  sonupperLimitValue: [
    // { required: true, message: "请输入控制范围上限值", trigger: "blur" },
    { validator: validator, trigger: "blur" },
  ],
  sonsamplingFrequency: [
    // { required: true, message: "请输入采样频度", trigger: "blur" },
    // { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonisGenerateWorkOrder: [
    // { required: true, message: "请选择是否生成工单", trigger: "change" },
  ],
  sonisSendMail: [],
  sonresponsiblePersonId: [
    { required: false, message: "请选择第一负责人", trigger: "change" },
  ],
  responsiblePersonId: [
    { required: true, message: "请选择第一负责人", trigger: "change" },
  ],
});

//校验
// function validator1(rule, value, callback: (a?: any) => {}) {
//   if (!value && value !== 0) {
//     //先判断空可以过
//     callback(new Error("请输入参数值"));
//   } else {
//     if (/^[+]{0,1}(\d+)$/.test(value)) {
//       //验证正整数和0的正则
//       return true;
//     } else {
//       callback(new Error("请输入数字"));
//     }
//   }
// }

function validator(rule, value, callback: (a?: any) => {}) {
  if (!value && value != "0") {
    //先判断空可以过
    return true;
    // callback(new Error("精度支持保留四位小数"));
  } else {
    if (/^[-\d]{1,7}(\.\d{0,4})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("精度支持保留四位小数"));
    }
  }
}

function validator1(rule, value, callback: (a?: any) => {}) {
  if (!value && value != "0") {
    //先判断空可以过
    // callback(new Error("精度支持保留两位小数"));
    return true;
  } else {
    if (/^\d{1,6}(\.\d{0,2})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("精度支持保留两位小数"));
    }
  }
}
const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  ElMessageBox.confirm("确认删除当前数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    formData.details.splice(index, 1);
    isValidated.value && formRef.value.validate(() => {});
  });
};

const details = {
  id: "",
  version: "",
  ruleId: "",
  parameterId: "",
  parameterName: "",
  parameterDesc: "",
  processDataType: "",
  parameterValue: "",
  lowerLimitValue: "",
  upperLimitValue: "",
  samplingFrequency: "",
  collectionFrequencyTime: "",
  collectionFrequencyUnit: "",
  isGenerateWorkOrder: "",
  isSendMail: "",
  responsiblePersonId: "",
  changeReason: "",
  changeReasonTime: "",
  responsiblePersonName: "",
  collectionFrequency: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  // let sondata = JSON.parse(JSON.stringify(details));
  // formData.details.push(sondata);

  if (!formData.equipId) {
    ElMessage.error("请先选择设备");
  } else {
    selectDialog.value.visible = true;
    if (formData.details.length > 0) {
      getBreakList();
    }
  }
};

const selectDialog = ref({
  visible: false,
});
const changeVisible = (val: any) => {
  // if (data) {
  //   formData.details = [];
  //   console.log("返回的数据", data);

  //   data.forEach((item) => {
  //     formData.details.push({
  //       parameterId: item.id,
  //       parameterDesc: item.parameterDesc,
  //       parameterName: item.parameterName,
  //       samplingFrequency: item.collectionFrequency,
  //       collectionFrequencyUnit: item.collectionFrequencyUnit,
  //       collectionFrequencyTime: item.collectionFrequencyTime,
  //     });
  //   });
  // }
  // selectDialog.value.visible = val;

  const elderDetails = JSON.parse(JSON.stringify(formData.details ?? []));

  if (val && val.length) {
    formData.details = [];

    val?.forEach((item: any) => {
      const current = elderDetails.filter(
        (self) => self.parameterId === item.id
      )?.[0];
      if (current) {
        formData.details.push(current);
      } else {
        formData.details.push({
          parameterId: item.id,
          parameterDesc: item.parameterDesc,
          parameterName: item.parameterName,
          samplingFrequency: item.collectionFrequency,
          collectionFrequencyUnit: item.collectionFrequencyUnit,
          collectionFrequencyTime: item.collectionFrequencyTime,
          isGenerateWorkOrder: 1,
          isSendMail: 1,
        });
      }
    });
  } else {
    formData.details = [];
  }
};

// 新增完返回的数据用于显示选择器
const breakList = ref([]);
const equipCodes = ref("");
const getBreakList = () => {
  breakList.value = [];
  equipCodes.value = formData.equipCode;
  formData.details.forEach((item: any) => {
    if (item.parameterId) {
      breakList.value.push({
        id: item.parameterId,
        parameterDesc: item.parameterDesc,
        parameterName: item.parameterName,
        collectionFrequency: item.samplingFrequency,
        collectionFrequencyUnit: item.collectionFrequencyUnit,
        collectionFrequencyTime: item.collectionFrequencyTime,
      });
    }
  });
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, {
        ...props.data,
        enabled: props.data.enabled == null ? 0 : props.data.enabled,
      });
      if (formData.id) {
        getdetails();
      }
      if (formData.projectId) {
        getProductModelList(formData.projectId);
      }
    }
    // 工序
    getProcessListByWorkshopSection();
    // 项目
    getProjectList();
    getEquipList();
    getProcessEquipList();
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  activeTabs.value = "监控参数详情";
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.id = "";
  formData.version = "";
  formData.processId = "";
  formData.processEquipId = "";
  formData.processEquipCode = "";
  formData.processCode = "";
  formData.workshopSectionCode = "";
  formData.workshopSectionName = "";
  formData.workshopSectionId = "";
  formData.partName = "";
  formData.processName = "";
  formData.equipId = "";
  formData.equipName = "";
  formData.equipCode = "";
  formData.projectId = "";
  formData.projectCode = "";
  formData.projectName = "";
  formData.productModel = "";
  formData.productModelCode = "";
  formData.productModelName = "";
  formData.programName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.responsiblePersonId = "";
  formData.responsiblePersonName = "";
  processList.value = [];

  projectList.value = [];
  productModelList.value = [];
}

const loading = ref(false);
const comparisonFields = [
  {
    field: "processDataType",
    name: "工艺数据类别",
    type: "dict",
    dict: "processDataType",
  },
  {
    field: "monitorDataType",
    name: "监控数据类型",
    type: "dict",
    dict: "PsmMonitorDataType",
  },
  {
    field: "parameterValue",
    name: "参考值",
    type: "input",
  },
  {
    field: "lowerLimitValue",
    name: "控制范围下限",
    type: "input",
  },
  {
    field: "upperLimitValue",
    name: "控制范围上限",
    type: "input",
  },
  {
    field: "samplingFrequency",
    name: "采样频度",
    type: "input",
  },
  // {
  //   field: "collectionFrequencyTime",
  //   name: "采样频度时间",
  //   type: "input"
  // },
  // {
  //   field: "collectionFrequencyUnit",
  //   name: "采样频度单位",
  //   type: "input"
  // },
  {
    field: "isGenerateWorkOrder",
    name: "生成工单",
    type: "switch",
  },
  {
    field: "isSendMail",
    name: "发送邮件",
    type: "switch",
  },
  {
    field: "responsiblePersonName",
    name: "第一负责人",
    type: "input",
  },
];

function compareObjectArrays(before, after) {
  const diffTextArray = [];
  // 如果 before 或 after 是空数组或 null/undefined，则使用空数组代替
  const safeBefore = Array.isArray(before) ? before : [];
  const safeAfter = Array.isArray(after) ? after : [];

  // 遍历 before 数组并对比 after 中的对象
  safeBefore.forEach((beforeItem) => {
    const afterItem = safeAfter.find(
      (item) => item.parameterDesc === beforeItem.parameterDesc
    );
    if (!afterItem) {
      diffTextArray.push(`删除参数: ${beforeItem.parameterDesc}`);
      return;
    }

    const cueText = ref("");
    // 对比每个属性
    for (const item of comparisonFields) {
      let beforeValue =
        item.type === "switch"
          ? !!beforeItem[item.field]
            ? "是"
            : "否"
          : item.type === "dict"
          ? dictionaryStore.filterDictName(item.dict, beforeItem[item.field])
          : beforeItem[item.field] ?? "空值";
      let afterValue =
        item.type === "switch"
          ? !!afterItem[item.field]
            ? "是"
            : "否"
          : item.type === "dict"
          ? dictionaryStore.filterDictName(item.dict, afterItem[item.field])
          : afterItem[item.field] ?? "空值";
      // 如果是采样频度 则需要特殊处理
      if (item.field === "samplingFrequency") {
        // 判断采样频度是否相同  采样时间和单位是否都相同
        if (
          beforeItem.samplingFrequency != afterItem.samplingFrequency ||
          beforeItem.collectionFrequencyTime !=
            afterItem.collectionFrequencyTime ||
          beforeItem.collectionFrequencyUnit !=
            afterItem.collectionFrequencyUnit
        ) {
          beforeValue = useDictionary(
            "ScaCollectFrequency",
            beforeItem[item.field]
          );
          if (beforeItem[item.field] == 2) {
            beforeValue =
              beforeValue +
              ` ${beforeItem.collectionFrequencyTime} ${
                beforeItem.collectionFrequencyUnit === "s" ? "秒" : "分钟"
              }`;
          }
          afterValue = useDictionary(
            "ScaCollectFrequency",
            afterItem[item.field]
          );
          if (afterItem[item.field] == 2) {
            afterValue =
              afterValue +
              ` ${afterItem.collectionFrequencyTime} ${
                afterItem.collectionFrequencyUnit === "s" ? "秒" : "分钟"
              }`;
          }
          if (!cueText.value) {
            cueText.value = `${beforeItem.parameterDesc}`;
          }
          cueText.value =
            cueText.value + ` ${item.name}由${beforeValue}改为${afterValue}`;
        }
      } else if (beforeItem[item.field] != afterItem[item.field]) {
        if (item.type === "switch") {
          if (!!beforeItem[item.field] != !!afterItem[item.field]) {
            if (!cueText.value) {
              cueText.value = `${beforeItem.parameterDesc}`;
            }
            cueText.value =
              cueText.value + ` ${item.name}由${beforeValue}改为${afterValue}`;
          }
        } else {
          if (!cueText.value) {
            cueText.value = `${beforeItem.parameterDesc}`;
          }
          cueText.value =
            cueText.value + ` ${item.name}由${beforeValue}改为${afterValue}`;
        }
      }
    }
    if (cueText.value) {
      cueText.value = cueText.value + ` 请确认此变更是否合理，并填写变更记录。`;
      diffTextArray.push(cueText.value);
    }
  });

  // 遍历 after 数组，查找在 before 中不存在的对象
  safeAfter.forEach((afterItem) => {
    const beforeItem = safeBefore.find(
      (item) => item.parameterDesc === afterItem.parameterDesc
    );
    if (!beforeItem) {
      diffTextArray.push(`新增参数: ${afterItem.parameterDesc}`);
    }
  });

  return {
    diffTextArray,
  };
}

const diffDialog = reactive({
  visible: false,
  title: "",
  diffTextArray: [],
  isReadonly: false,
});
const changeRecordDialog = reactive({
  visible: false,
  title: "",
  id: "",
  isReadonly: false,
});

const changeDiffVisible = (val: any) => {
  diffDialog.visible = val;
  if (val) {
    diffDialog.diffTextArray = [];
  }
};
const changeChangeRecordVisible = (val: any) => {
  changeRecordDialog.visible = val;
  if (val) {
    changeRecordDialog.id = "";
  }
};

/** 工艺参数监控规则保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      if (
        formData.id &&
        (formData.details.length > 0 || detailCache.value.length > 0)
      ) {
        const diff = compareObjectArrays(detailCache.value, formData.details);
        if (diff.diffTextArray.length > 0) {
          diffDialog.visible = true;
          diffDialog.diffTextArray = diff.diffTextArray;
          diffDialog.title = "修改对比";
          diffDialog.isReadonly = false;
          loading.value = false;
          return;
        }
      }

      const text = formData.id ? "编辑" : "新增";

      await request({
        url: "/dmpDosPcm/psmparammonitorrule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const diffSubmit = async (diffFormData: any) => {
  console.log(diffFormData);
  formData.changeReason = diffFormData.remarks;
  formData.changeReasonTime = diffFormData.createTime;
  await request({
    url: "/dmpDosPcm/psmparammonitorrule/updateAndSaveHis",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`编辑成功`);
  // closeDialog();
  // emit("reset-table", formData.id);
};

const openChangeRecordDialog = (id) => {
  changeRecordDialog.visible = true;
  changeRecordDialog.title = "变更记录";
  changeRecordDialog.id = id;
  changeRecordDialog.isReadonly = false;
};

const detailCache = ref([]);

async function getdetails() {
  laodingTable.value = true;
  let sondetails = await request({
    url: "/dmpDosPcm/psmparammonitorrule/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    laodingTable.value = false;
  });
  formData.details = sondetails.data;
  detailCache.value = JSON.parse(JSON.stringify(formData.details));
}
// 获取工艺列表
const processList = ref([]);
const getProcessList = async () => {
  await request({
    url: `mdm/mdmprocess/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    processList.value = res.data;
  });
};
const getProcessListByWorkshopSection = async () => {
  if (formData.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: formData.workshopSectionId },
    }).then((res) => {
      processList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processCode,
          }))
        : [];
    });
  } else {
    await getProcessList();
  }
};
// 改变工艺路线时
const changeProcess = () => {
  formData.processEquipId = "";
  if (formData.processId) {
    processList.value.forEach((item: any) => {
      if (item.id == formData.processId) {
        formData.processName = item.processName;
        formData.processCode = item.processCode;
      }
    });
  } else {
    formData.processName = "";
    formData.processCode = "";
  }
  getProcessEquipList();
  changeProcessEquip();
};

// 获取工段
const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
// 改变工艺路线时
const changeWorkshopSection = () => {
  formData.processId = "";
  formData.processCode = "";
  processList.value = [];
  formData.responsiblePersonId = "";
  formData.responsiblePersonName = "";
  userList.value = [];
  formData.details.map((self: any) => {
    self.responsiblePersonId = "";
    self.responsiblePersonName = "";
  });
  if (formData.workshopSectionId) getUserList(formData.workshopSectionId);
  const find = workshopSectionList.value.find(
    (item) => item.id === formData.workshopSectionId
  );
  formData.workshopSectionCode = find?.workshopSectionCode;
  formData.workshopSectionName = find?.workshopSectionName;
  getProcessListByWorkshopSection();
  changeProcess();
};

// 根据工艺获取设备列表
// 获取工艺列表
const equipList = ref([]);
const getEquipList = async () => {
  await request({
    url: "/iotadmin/scaequipinfo/getList",
    method: "post",
    data: {
      processId: formData.processId,
      processEquipId: formData.processEquipId,
      workshopSectionId: formData.workshopSectionId,
    },
  }).then((res) => {
    equipList.value = res.data;
    filteredOptions.value = res.data;
  });
};

const filteredOptions = ref<any>([]);
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...equipList.value];
    return;
  }
  filteredOptions.value = equipList.value.filter((option: any) => {
    return option?.equipName?.toLowerCase().includes(query.toLowerCase());
  });
}, 300); // 延迟 300ms

// 根据工艺获取设备列表
// 获取工艺列表
const filteredOptions1 = ref<any>([]);
const processEquipList = ref([]);
const getProcessEquipList = async () => {
  await request({
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {
      processId: formData.processId,
      workshopSectionId: formData.workshopSectionId,
    },
  }).then((res) => {
    processEquipList.value = res.data;
    filteredOptions1.value = [...processEquipList.value];
  });
};
const customFilter1 = _.debounce((query: any) => {
  if (!query) {
    filteredOptions1.value = [...processEquipList.value];
    return;
  }
  filteredOptions1.value = processEquipList.value.filter((option: any) => {
    return option?.equipCode?.toLowerCase().includes(query.toLowerCase());
  });
}, 300); // 延迟 300ms

const changeProcessEquip = () => {
  getEquipList();
  formData.equipId = "";
  formData.equipName = "";
  formData.equipCode = "";
};

const changeEquip = (e: string) => {
  if (e) {
    equipList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.equipName = item.equipName;
        formData.equipCode = item.equipCode;
        console.log(item, formData.equipName, formData.equipCode);
      }
    });
  } else {
    formData.equipName = "";
    formData.equipCode = "";
  }
};

// 获取项目列表
const projectList = ref([]);
const getProjectList = async () => {
  await request({
    url: `mdm/mdmprojectinfo/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    projectList.value = res.data;
  });
};
// 改变项目列表
const changeProject = (e: string) => {
  productModelList.value = [];
  formData.productModel = "";
  formData.productName = "";
  formData.productCode = "";
  if (e) {
    processList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.projectName = item.projectName;
        formData.projectCode = item.projectCode;
      }
    });
    getProductModelList(e);
  } else {
    formData.projectName = "";
    formData.projectCode = "";
  }
};

// 根据项目获取产品型号
// 获取产品型号
const productModelList = ref([]);
const getProductModelList = async (id: string) => {
  await request({
    url: "mdm/mdmproductinfo/getList",
    method: "post",
    data: { projectId: id },
  }).then((res) => {
    productModelList.value = res.data;
  });
};

const changeProductModel = (e: string) => {
  if (e) {
    productModelList.value.forEach((item: any) => {
      if (item.productCode == e) {
        formData.productModelName = item.productName;
        formData.productModelCode = item.productCode;
      }
    });
  } else {
    formData.productModelName = "";
    formData.productModelCode = "";
    formData.productModel = "";
  }
};

// 获取设备参数
const parameterList = ref([]);
const getParameterList = async () => {
  await request({
    url: `iotadmin/scaequipcollectionparam/getProcessParamList`,
    method: "post",
    data: {},
  }).then((res) => {
    parameterList.value = res.data;
  });
};
// 设备参数 改变
const changeParameter = (e: string, index: number) => {};

// 负责人
const userList = ref([]);
const getUserList = async (workshopSectionId?: any) => {
  await request({
    url: "/dmpDosPcm/psmprocessdutyuser/getDetailsByWorkshopSectionId",
    method: "post",
    data: {
      workshopSectionId: workshopSectionId || "",
      userType: 3,
    },
  }).then((res) => {
    userList.value = res.data;
  });
};

// 负责人 改变
const changePerson = (e, index) => {
  if (e) {
    userList.value.forEach((item: any) => {
      if (item.userId == e) {
        formData.details[index].responsiblePersonName = item.userName;
      }
    });
  } else {
    formData.details[index].responsiblePersonName = "";
  }
};

const changeResponsible = (e: any) => {
  if (e) {
    const current: any =
      userList.value?.filter((item: any) => item.userId === e)[0] || {};
    formData.responsiblePersonName = current.userName || "";
  } else {
    formData.responsiblePersonName = "";
  }
};
const activeTabs = ref<number | string>("监控参数详情");

const handleTabClick = (v1) => {
  if (v1.paneName === "变更记录") {
    eventBusEmit("PSM-PARAM-MONITOR-RULE-ALL-CHANGE-RECORD", formData.id);
  }
};

// watch(() => activeTabs.value,(val) => {
//   if (val === "变更记录") {
//     eventBusEmit("PSM-PARAM-MONITOR-RULE-ALL-CHANGE-RECORD", formData.id)
//   }
//   })

onMounted(() => {
  // 工序
  getProcessListByWorkshopSection();
  // 设备
  getEquipList("");
  getProcessEquipList();
  // 项目
  getProjectList();
  // 负责人
  getUserList();
  getWorkshopSectionList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  // :deep(.el-scrollbar__wrap) {
  //   max-height: 400px;
  //   overflow-y: auto;
  // }
  :deep(.el-input-group__append) {
    padding: 0 8px !important;
  }
}
.formTable3 {
  :deep(.el-scrollbar__wrap) {
    max-height: 400px;
    overflow-y: auto;
  }
}
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 116px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
:deep(.el-descriptions__cell) {
  padding: 12px;
}
:deep(.el-table--default .cell) {
  padding: 0 6px;
}
:deep(.switchLable .el-form-item__content) {
  justify-content: center;
}
:deep(.el-dialog__body) {
  padding: 20px;
}
:deep(.el-button + .el-button) {
  margin-left: 6px;
  svg {
    padding-right: 0px;
    margin-right: 0px;
  }
}
</style>
